package com.iweb.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iweb.annotation.TokenAuthentication;
import com.iweb.common.jwt.JwtUtil;
import com.iweb.common.result.EmptyObject;
import com.iweb.common.result.ResultEntity;
import com.iweb.model.Member;
import com.iweb.service.MemberService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 会员 前端控制器
 * </p>
 *
 * @author jack
 * @since 2020-05-15
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("会员登录")
    @PostMapping("login")
    public ResultEntity login(@RequestBody Member member, HttpServletResponse resp) {
        // 查询用户
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", member.getMobile()).or().eq("email", member.getEmail());
        Member memberData = memberService.getOne(queryWrapper);
        // 用户登录验证
        if (ObjectUtil.isEmpty(memberData)) {
            return ResultEntity.FAIL_LOGIN_USERNAME();
        } else if (passwordEncoder.matches(member.getPassword(), memberData.getPassword())) {
            // 生成token
            String token = JwtUtil.createJWT(memberData.getId(), memberData.getMobile(), null);
            // 将token添加到头部
            resp.addHeader("token", token);
            resp.setHeader("Access-Control-Expose-Headers", "token");
            return ResultEntity.SUCCESS(memberData);
        } else {
            return ResultEntity.FAIL_LOGIN_PASSWORD();
        }
    }

    @ApiOperation("会员注册")
    @PostMapping("reg")
    public ResultEntity<EmptyObject> reg(@RequestBody Member member) {

        // 判断用户是否已经注册
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("mobile", member.getMobile())
                .or()
                .eq("email", member.getEmail());
        List<Member> list = memberService.list(queryWrapper);
        if (list.size() > 0) {
            return ResultEntity.FAIL_REG_USER();
        }
        // 密码加密
        member.setPassword(passwordEncoder.encode(member.getPassword()));
        // 设置注册时间
        member.setRegisterDate(LocalDateTime.now());
        // 设置粉丝数默认值
        member.setFansCount(0);
        // 设置关注数默认值
        member.setFollowCount(0);
        // 设置默认头像
        member.setAvatar("static/images/1_qq_28244771.gif");
        boolean flag = memberService.save(member);
        if (flag) {
            return ResultEntity.SUCCESS();
        } else {
            return ResultEntity.FAIL();
        }
    }

    @TokenAuthentication
    @ApiOperation("修改会员基本信息")
    @PutMapping("{id}")
    public ResultEntity<EmptyObject> updateMember(@PathVariable String id,
                                                  @RequestBody Member member) {
        member.setId(id);
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>(member);
        boolean flag = memberService.updateById(member);
        if (flag) {
            return ResultEntity.SUCCESS();
        } else {
            return ResultEntity.FAIL();
        }
    }

    @TokenAuthentication
    @ApiOperation("获取登录用户的信息")
    @GetMapping("getInfo")
    public ResultEntity<Member> getInfo() {
        // 从token中获取userId
        HttpServletRequest request =
                ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String userId = String.valueOf(request.getAttribute("userId"));
        Member member = memberService.getById(userId);
        return ResultEntity.SUCCESS(member);
    }


}

